﻿using ELearning.BLL;
using ELearning.API;
using ELearning.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ELearning.API.Controllers.ExamControllers;
using ELearning.Common;

namespace ExamTimeOutDetection
{
    class Service
    {
        EExamService examService => new EExamService();
        EStuScoreService stuScoreService => new EStuScoreService();
        EStuExamService stuExamService => new EStuExamService();

        public void Run()
        {
            try
            {
                var data = examService.GetExamTimeOutStu();
                foreach (var item in data.Data)
                {
                    SubmitPaperBySys(item.Fid);
                }
            }
            catch (Exception ex)
            {

            }
        }

        /// <summary>
        /// 学员考试超时检测-保存答题未提交
        /// 系统提交
        /// </summary>
        /// <param name="Fid"></param>
        /// <returns></returns>
        public bool SubmitPaperBySys(Guid Fid)
        {
            var sScore = stuScoreService.Find(x => !x.IsDelete && x.ID == Fid);
            if (sScore == null) return false;
            if (sScore.StudyState == 3) return false;

            List<EStuExam> stuExamsUp = new List<EStuExam>();

            var stuExams = stuExamService.FindList(x => !x.IsDelete && x.Fid == Fid).ToList();

            var qIds = new List<Guid>();//stuExams.Select(x => x.Qid).ToList();

            var qnAInfos = examService.GetPaperAnswer(qIds, sScore.Pid);

            foreach (var a in stuExams)
            {
                var qna = qnAInfos.Find(x => x.QnAID == a.Qid);
                int IsOk = 0; //StudyAnswerEnum.Other.IntValue();
                double Scored = 0;

                if (a.StuAnswer == null || a.StuAnswer == "") IsOk = 3;// StudyAnswerEnum.None.IntValue();
                else if (a.StuAnswer == qna.QAnswer)
                {
                    IsOk = 1;// StudyAnswerEnum.Right.IntValue();
                    Scored = qna.QScore;
                }
                else IsOk = 2;// StudyAnswerEnum.Wrong.IntValue();

                a.IsOk = IsOk;
                a.Scored = Scored;
                a.Modifyer = "答题超时-系统自动提交";
                a.ModifyTime = DateTime.Now;
                sScore.TotalScore += Scored;
            }

            stuExamService.Updates(stuExams);

            sScore.EndTime = DateTime.Now;
            sScore.StudyState = 3;//StudyStateEnum.Finished.IntValue();
            sScore.ModifyTime = DateTime.Now;
            sScore.Modifyer = "答题超时-系统自动提交";
            stuScoreService.Update(sScore);

            return true;
        }


    }

}
